package de.arndt_panzer.bensgallery;

import java.io.File;
import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnGenericMotionListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.VideoView;

public class MainActivity extends BensGalleryActivityBase {

	GalleryImageAdapter mGalleryAdapter;
	BensMediaController mMediaController;
	Gallery mGallery;
	VideoView mVideoView;
	String mCurrentPlayBack;
	ImageButton mBtnDelete;
	Integer mLastLongClick;
	ImageButton mStopVideo;

	private class BensMediaController extends MediaController {

		@Override
		public void hide() {
			// TODO Auto-generated method stub
			super.hide();
			mStopVideo.setVisibility(View.INVISIBLE);
		}

		@Override
		public void show() {
			super.show();
			hidePlayButtonChilds(this);
			mStopVideo.setVisibility(View.VISIBLE);
		}

		@Override
		public void show(int timeout) {
			super.show(timeout);
			hidePlayButtonChilds(this);
			mStopVideo.setVisibility(View.VISIBLE);
		}

		private void hidePlayButtonChilds(View view) {
			if (!(view instanceof ViewGroup)) {
				// reached widget level
				if (!(view instanceof SeekBar))
					view.setVisibility(View.GONE);
				return;
			}
			ViewGroup group = (ViewGroup) view;
			for (int i = 0; i < group.getChildCount(); ++i) {
				hidePlayButtonChilds(group.getChildAt(i));
			}

		}

		public BensMediaController(Context context) {
			super(context);
		}

		@Override
		public void setMediaPlayer(MediaPlayerControl player) {
			super.setMediaPlayer(player);
			this.show();
		}
	}

	private class VideoPositionHolder {
		public int Position;
		public String MediaPath;

		public VideoPositionHolder(int pos, String path) {
			Position = pos;
			MediaPath = path;
		}
	}

	final ArrayList<VideoPositionHolder> mVideoPos = new ArrayList<MainActivity.VideoPositionHolder>();

	private int getVideoPosition(String mediaPath) {
		for (VideoPositionHolder h : mVideoPos) {
			if (h.MediaPath != null && h.MediaPath.equals(mediaPath)) {
				return h.Position;
			}
		}
		return 0;
	}

	private void updateVideoPosition(int pos, String path) {
		for (VideoPositionHolder h : mVideoPos) {
			if (h.MediaPath != null && h.MediaPath.equals(path)) {
				h.Position = pos;
				return;
			}
		}
		mVideoPos.add(new VideoPositionHolder(pos, path));
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);

		mGallery = (Gallery) findViewById(R.id.gallery_main);
		mVideoView = (VideoView) findViewById(R.id.video_main);
		mBtnDelete = (ImageButton) findViewById(R.id.imageButton_delete);
		mStopVideo = (ImageButton) findViewById(R.id.imageButton_stopVideo);

		mBtnDelete.setVisibility(View.INVISIBLE);
		mBtnDelete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mBtnDelete.setVisibility(View.INVISIBLE);
				if (mLastLongClick == null)
					return;
				File longClickedFile = new File(mGalleryAdapter
						.getItem(mLastLongClick));
				if (longClickedFile.delete()) {
					Toast.makeText(
							MainActivity.this,
							BitmapHelper.isMovie(longClickedFile) ? "Video gelöscht :-("
									: "Bild gelöscht :-(", Toast.LENGTH_LONG)
							.show();
				}
				mGalleryAdapter.requestImageUpdate();
				mLastLongClick = null;
			}
		});

		mStopVideo.setVisibility(View.INVISIBLE);
		mStopVideo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mVideoView.pause();
				updateVideoPosition(mVideoView.getCurrentPosition(),
						mCurrentPlayBack);
				mCurrentPlayBack = null;
				mVideoView.stopPlayback();
				mVideoView.setVisibility(View.GONE);
				mStopVideo.setVisibility(View.INVISIBLE);
				mGallery.setVisibility(View.VISIBLE);
				mMediaController.hide();
			}
		});

		// initialize gallery adapter
		int[] winSize = getWindowSize();
		mGalleryAdapter = new GalleryImageAdapter(this, winSize[0] / 4,
				winSize[1] / 4) {

			@Override
			public View getView(int index, View view, ViewGroup viewGroup) {
				mLastLongClick = null;
				mBtnDelete.setVisibility(View.INVISIBLE);
				return super.getView(index, view, viewGroup);
			}
		};
		mGallery.setAdapter(mGalleryAdapter);

		/*
		 * GALLERY EVENTS
		 */
		mGallery.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> rootView, View itemView,
					int position, long id) {
				mLastLongClick = null;
				mBtnDelete.setVisibility(View.INVISIBLE);
				String mediaPath = mGalleryAdapter.getItem(position);
				ImageView imageView = (ImageView) itemView
						.findViewById(R.id.imageView);
				if (mediaPath != null && imageView != null) {
					if (BitmapHelper.isMovie(new File(mediaPath))) {
						// hide gallery
						mGallery.setVisibility(View.GONE);
						mVideoView.setVisibility(View.VISIBLE);
						mMediaController.show(10);

						// start play back
						int pos = getVideoPosition(mediaPath);
						mVideoView.setVideoPath(mediaPath);
						mCurrentPlayBack = mediaPath;
						mVideoView.start();
						mVideoView.seekTo(pos);
					}
				}
			}
		});

		mGallery.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> gallery,
					View layoutView, int pos, long id) {
				mLastLongClick = pos;
				mBtnDelete.setVisibility(View.VISIBLE);
				return true;
			}

		});

		// initialize media controller
		mMediaController = new BensMediaController(this);
		mVideoView.setMediaController(mMediaController);

		/*
		 * VIDEO VIEW EVENTS
		 */
		mVideoView.setOnCompletionListener(new OnCompletionListener() {

			@Override
			public void onCompletion(MediaPlayer mp) {
				if (mCurrentPlayBack != null) {
					updateVideoPosition(0, mCurrentPlayBack);
				}
				mVideoView.setVisibility(View.GONE);
				mGallery.setVisibility(View.VISIBLE);
				mMediaController.hide();
			}
		});

	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		mGalleryAdapter.requestImageUpdate();
	}

	@Override
	public boolean handleMessage(Message msg) {
		Bundle data = msg.getData();
		if (data == null)
			return false;
		String action = data.getString("action");
		if (action == null)
			return false;

		// check the action code
		if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
			// external memory card mounted
			mGalleryAdapter.requestImageUpdate();
			mVideoPos.clear();
		} else if (action.equals(Intent.ACTION_SCREEN_ON)) {
			// screen switched on
			mGalleryAdapter.requestImageUpdate();
			mVideoPos.clear();
		} else if (action.equals(Intent.ACTION_CONFIGURATION_CHANGED)) {
			// display rotated
			if (mVideoView.getVisibility() == View.VISIBLE
					&& (mVideoView.canSeekForward() || mVideoView
							.canSeekBackward())) {
				mVideoView.pause();
				int pos = mVideoView.getCurrentPosition();
				mVideoView.stopPlayback();
				mVideoView.setVisibility(View.GONE);
				mVideoView.requestLayout();
				mVideoView.setVisibility(View.VISIBLE);
				mVideoView.requestLayout();
				mVideoView.start();
				mVideoView.seekTo(pos);
			}
		} else {
			Log.d(TAG, "handleMessage(): Unknown action " + action);
			return false;
		}
		return true;
	}
}
